package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.model.Spit;
import com.tensquare.util.IdWorker;
import com.tensquare.util.NotNullHelps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SpitService {

    private String collectionName = "spit";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SpitDao spitDao;


    public void deleteById(String id) {
        spitDao.deleteById(id);
    }

    public void update(Spit spit) {
        spitDao.save(spit);
    }

    public void save(Spit spit) {
        spit.set_id(idWorker.nextId().toString());
        spit.setPublishtime(new Date());
        spit.setShare(0);
        spit.setVisits(0);
        spit.setThumbup(0);
        spit.setComment(0);
        spit.setState("1");
        String parentId = spit.getParentid();
        if (NotNullHelps.isNotNull(parentId) == true) {
            Query query = new Query();
            Criteria idCondition = Criteria.where("_id").is(parentId);
            query.addCriteria(idCondition);
            Update mongoUpdate = new Update();
            mongoUpdate.inc("comment", 1);
            mongoTemplate.updateFirst(query, mongoUpdate, collectionName);
        }
        spitDao.save(spit);
    }

    public Spit findById(String id) {
        return spitDao.findById(id).get();
    }

    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    public Page<Spit> findByParentId(String parentId, Integer page, Integer size) {
        Pageable pageData = PageRequest.of(page - 1, size);
        return spitDao.findByParentid(parentId, pageData);
    }

    public void thumbup(String spitId) {
        Spit spit = spitDao.findById(spitId).get();
        if (NotNullHelps.isNotNull(spit) == true) {
            Integer thumbup = spit.getThumbup();
            thumbup = NotNullHelps.isNotNull(thumbup) ? thumbup + 1 : 1;
            spit.setThumbup(thumbup);
            spitDao.save(spit);
        }
    }

    public void thumbupTemplate(String spitId) {
        Query query = new Query();
        Criteria idCondition = Criteria.where("_id").is(spitId);
        query.addCriteria(idCondition);
        Update mongoUpdate = new Update();
        mongoUpdate.inc("thumbup", 1);
        mongoTemplate.updateFirst(query, mongoUpdate, collectionName);

    }

}
